//
//  ViewController.m
//  EquesCat
//
//  Created by Chun Hung Cheung on 2024/12/17.
//

#import "LoginViewController.h"
#import <EquesBusiness/YKBusinessFramework.h>
#import <EquesBusiness/YKIPinfo.h>
#import "AppDelegate.h"

@interface LoginViewController ()<UITextFieldDelegate>
@property(nonatomic,strong)UIImageView *logo_image_view;
@property(nonatomic,strong)UITextField *user_textfield;
@property(nonatomic,strong)UITextField *pwd_textfield;
@property(nonatomic,strong)UIButton *loginButton;

@property(nonatomic,strong)UIButton *register_btn;
@property(nonatomic,copy)NSString *token;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     self.view.backgroundColor = [UIColor whiteColor];
    
     self.logo_image_view.image = [UIImage imageNamed:@"login_v3_logo"];

    /*注册websocket通知 用于接受消息回调 必须注册*/
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginResult:) name:equesOnMessageResultNotification object:nil];
    
    self.user_textfield.textColor = [HexChangeRGB colorWithHexString:@"#333333"];
    NSString *holderText = NSLocalizedString(@" 输入用户名", nil);
    NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc] initWithString:holderText];
    [placeholder addAttribute:NSForegroundColorAttributeName value:[HexChangeRGB colorWithHexString:@"#999999"] range:NSMakeRange(0, holderText.length)];
    [placeholder addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17.0] range:NSMakeRange(0, holderText.length)];
    self.user_textfield.attributedPlaceholder = placeholder;
    
    
    NSString *holderText1 = NSLocalizedString(@" 用户密码", nil);
    NSMutableAttributedString *placeholder1 = [[NSMutableAttributedString alloc] initWithString:holderText1];
    [placeholder1 addAttribute:NSForegroundColorAttributeName value:[HexChangeRGB colorWithHexString:@"#999999"] range:NSMakeRange(0, holderText1.length)];
    [placeholder1 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17.0] range:NSMakeRange(0, holderText1.length)];
     self.pwd_textfield.attributedPlaceholder = placeholder1;

    [self.loginButton setTitle:NSLocalizedString(@"登录", nil) forState:UIControlStateNormal];
 
    
    
      //用户注册和忘记密码
     [self.register_btn setTitle:NSLocalizedString(@"注册", nil) forState:UIControlStateNormal];
     
}

- (void)loginResult:(NSNotification *)notification
{
    NSDictionary *loginresult = [notification object];
    
    NSLog(@"loginResult--->%@",loginresult);
    
    NSString *strMethod = [loginresult objectForKey:@"method"];
    int code = [[loginresult objectForKey:@"code"] intValue];
    if ([strMethod isEqualToString:@"login_v2"]){
        
    
        if (code == 4000) {
            [SVProgressHUD dismiss];
            
            [SVProgressHUD showSuccessWithStatus:@"登录成功"];
        
             YKIPinfo *info = [[YKIPinfo bg_find:@"YKIPinfo" where:nil] firstObject];
             info.user = self.user_textfield.text;
             info.pwd = self.token;
             info.auto_login = YES;
            [info bg_saveOrUpdate];
            
            //获取用户名名下的设备
            [YKBusinessFramework equesGetDeviceList];
            
            [self changeView];
        }else{
            
             NSString *reason = [loginresult objectForKey:@"reason"];
            [SVProgressHUD showErrorWithStatus:reason duration:3];
        }
    }
    
}


- (UIImageView*)logo_image_view
{
    if (!_logo_image_view) {
         _logo_image_view = [[UIImageView alloc]init];
        [self.view addSubview:_logo_image_view];
        [_logo_image_view mas_makeConstraints:^(MASConstraintMaker *make) {
             make.width.height.mas_equalTo(80);
             make.centerX.equalTo(self.view.mas_centerX);
             make.top.equalTo(self.view.mas_top).offset(150);
        }];
    }
    return _logo_image_view;
}


#pragma mark: 用户名输入框
- (UITextField*)user_textfield
{
    if (!_user_textfield) {
         _user_textfield = [[UITextField alloc]init];
        [_user_textfield addTarget:self action:@selector(passwordDidChange:) forControlEvents:UIControlEventEditingChanged];
         _user_textfield.tag = 201;
         _user_textfield.delegate = self;
         [self.view addSubview:_user_textfield];
         _user_textfield.borderStyle = UITextBorderStyleNone;
         _user_textfield.layer.cornerRadius = 8;
         _user_textfield.layer.masksToBounds = YES;
         _user_textfield.backgroundColor = [HexChangeRGB colorWithHexString:@"#F2F2F2"];
        [_user_textfield mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(50);
            make.right.equalTo(self.view.mas_right).offset(-38);
            make.left.equalTo(self.view.mas_left).offset(38);
            make.top.equalTo(self.logo_image_view.mas_bottom).offset(40);
        }];
    }
    return _user_textfield;
}


#pragma mark: 用户输入框变化
- (void)passwordDidChange:(UITextField*)textfield
{
    if (self.pwd_textfield.text.length > 0 && textfield.text.length > 0) {
        
         self.loginButton.backgroundColor = [HexChangeRGB colorWithHexString:@"#ff7316"];
         self.loginButton.userInteractionEnabled = YES;
            
    }else{
        
        self.loginButton.backgroundColor = [HexChangeRGB colorWithHexString:@"#F8A966"];
        self.loginButton.userInteractionEnabled = NO;
    }
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}



#pragma mark: 密码输入框
- (UITextField*)pwd_textfield
{
     if (!_pwd_textfield) {
          _pwd_textfield = [[UITextField alloc]init];
          _pwd_textfield.tag = 101;
          _pwd_textfield.delegate = self;
         [self.view addSubview:_pwd_textfield];
          _pwd_textfield.borderStyle = UITextBorderStyleNone;
         _pwd_textfield.layer.cornerRadius = 8;
        [_pwd_textfield addTarget:self action:@selector(usernameTextfieldDidChange:) forControlEvents:UIControlEventEditingChanged];
         _pwd_textfield.layer.masksToBounds = YES;
         _pwd_textfield.secureTextEntry = YES;
         _pwd_textfield.backgroundColor = [HexChangeRGB colorWithHexString:@"#F2F2F2"];
        [_pwd_textfield mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(50);
            make.right.equalTo(self.view.mas_right).offset(-38);
            make.left.equalTo(self.view.mas_left).offset(38);
            make.top.equalTo(self.user_textfield.mas_bottom).offset(20);
        }];
    }
    return _pwd_textfield;
}

#pragma mark: 密码输入框变化
- (void)usernameTextfieldDidChange:(UITextField*)textfield
{
    if (self.user_textfield.text.length > 0 && textfield.text.length > 0) {
        
         self.loginButton.backgroundColor = [HexChangeRGB colorWithHexString:@"#ff7316"];
         self.loginButton.userInteractionEnabled = YES;
        
    }else{
        self.loginButton.backgroundColor = [HexChangeRGB colorWithHexString:@"#F8A966"];
        self.loginButton.userInteractionEnabled = NO;
    }
}

-(UIButton*)loginButton
{
   if (!_loginButton) {
        _loginButton = [[UIButton alloc]init];
        _loginButton.userInteractionEnabled = NO;
        _loginButton.backgroundColor = [HexChangeRGB colorWithHexString:@"#F8A966"];
        _loginButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:20.0];
       [_loginButton setTitleColor:[HexChangeRGB colorWithHexString:@"#FFFFFF"] forState:UIControlStateNormal];
       [_loginButton addTarget:self action:@selector(loginButtonClick) forControlEvents:UIControlEventTouchUpInside];
       [self.view addSubview:_loginButton];
       [_loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
           make.top.equalTo(self.pwd_textfield.mas_bottom).offset(50);
           make.height.mas_equalTo(50);
           make.left.equalTo(self.view.mas_left).offset(37);
           make.right.equalTo(self.view.mas_right).offset(-37);
       }];
       _loginButton.layer.cornerRadius = 25;
       _loginButton.layer.masksToBounds = YES;
   }
   return _loginButton;
}

#pragma mark: 登录按钮点击
- (void)loginButtonClick
{
    [self.user_textfield resignFirstResponder];
    [self.pwd_textfield resignFirstResponder];
    
    [YKBusinessFramework equesLogout];
    
    [SVProgressHUD showWithStatus:@"开始登录" duration:15 completionBlock:^{
        
    }];
    
    if (self.user_textfield.text.length > 0 && self.pwd_textfield.text.length > 0) {
   
    YKIPinfo *newinfo = [[YKIPinfo bg_find:@"YKIPinfo" where:nil] firstObject];
    
    NSDictionary *dcit = [YKBusinessFramework get_token_user_info:ThirdPartyDemoBrand appkey:ThirdPartyDemoAppKey user_name:self.user_textfield.text];
    
    [AFNHTTPSRequest httpsPostRequestWithUrl:[YKBusinessFramework get_user_token] errorHint:^(id errorData) {
        NSLog(@"errorData--%@",errorData);
    } deleteDic:dcit isFavorite:YES result:^(id data) {
        NSLog(@"data--%@",data);
        /*
         {
         "reason" : "success",
         "data" : "$d894aaf7f24d563be0345725f31a1ea7",
         "code" : 0
         }
         */
        //存在
        if ([[data objectForKey:@"code"] intValue] == 0) {
            
            if (newinfo) {
                 newinfo.user = self.user_textfield.text;
                 newinfo.pwd = [data objectForKey:@"data"];
                [newinfo bg_saveOrUpdate];
            }
            NSString *token = [data objectForKey:@"data"];
            
            if ([token hasPrefix:@"$"]) {
                token = [token substringFromIndex:1];
            }
          
            
            [YKBusinessFramework loginWithUserName:self.user_textfield.text token:token appKey:ThirdPartyDemoAppKey server_adds:SERVER_ADDRS];
            
            //去注册
        }else{
            
            
            NSDictionary *dict = [YKBusinessFramework register_user_info:ThirdPartyDemoBrand appkey:ThirdPartyDemoAppKey user_name:self.user_textfield.text];
            
            [AFNHTTPSRequest httpsPostRequestWithUrl:[YKBusinessFramework register_user] errorHint:^(id  _Nonnull errorData) {
                NSLog(@"errorData -- %@",errorData);
            } deleteDic:dict isFavorite:YES result:^(id  _Nonnull data) {
                NSLog(@"data -- %@",data);
                
                if ([[data objectForKey:@"code"] intValue] == 0) {
                    
                    
                    [SVProgressHUD showSuccessWithStatus:@"注册成功！"];
                    
                    NSString *token = [data objectForKey:@"data"];
                    
                    if ([token hasPrefix:@"$"]) {
                        token = [token substringFromIndex:1];
                    }
                    
                    
                    if (newinfo) {
                         newinfo.user = self.user_textfield.text;
                         newinfo.pwd = token;
                        [newinfo bg_saveOrUpdate];
                    }
                    
                    [SVProgressHUD showSuccessWithStatus:@"开始登录"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                       
                        [YKBusinessFramework loginWithUserName:self.user_textfield.text token:token appKey:ThirdPartyDemoAppKey server_adds:SERVER_ADDRS];
                    });
                    
                }else if ([[data objectForKey:@"code"] intValue] == 4404){
                    
                    
                    [SVProgressHUD showErrorWithStatus:@"用户已注册"];
                    
                }else{
                    
                    [SVProgressHUD showErrorWithStatus:[data objectForKey:@"reason"]];
                    
                }
                
                /*
                 data -- {
                 code = 0;
                 data = f358783c7bea2c9a626dce7706627d4c; // 注册成功返回的token
                 reason = success;
                 }
                 */
                
            }];
            
        }
        
    }];
    
  }
}




#pragma mark 登录成功，切换画面，项目基本主界面
- (void)changeView
{
     // 去掉监听通知
     [[NSNotificationCenter defaultCenter] removeObserver:self name:equesOnMessageResultNotification object:nil];
    
     AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    [delegate login_sucess];

}


-(UIButton*)register_btn
{
   if (!_register_btn) {
       _register_btn = [[UIButton alloc]init];
       _register_btn.backgroundColor = [HexChangeRGB colorWithHexString:@"#00C6FB"];
       _register_btn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:20.0];
      [_register_btn setTitleColor:[HexChangeRGB colorWithHexString:@"#FFFFFF"] forState:UIControlStateNormal];
      [_register_btn addTarget:self action:@selector(register_btnClick) forControlEvents:UIControlEventTouchUpInside];
      [self.view addSubview:_register_btn];
      [_register_btn mas_makeConstraints:^(MASConstraintMaker *make) {
          make.top.equalTo(self.loginButton.mas_bottom).offset(40);
          make.height.mas_equalTo(50);
          make.left.equalTo(self.view.mas_left).offset(37);
          make.right.equalTo(self.view.mas_right).offset(-37);
      }];
       _register_btn.layer.cornerRadius = 25;
       _register_btn.layer.masksToBounds = YES;
   }
   return _register_btn;
}

- (void)register_btnClick
{
      /*
       1. register_user_info 获取注册数据 1 品牌ID appkey：分配给厂商的 user_name 注册的用户吗
       
       */
    
    if (self.user_textfield.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入用户名"];
        return;
    }
    
    [SVProgressHUD showWithDuration:10];
    
    NSDictionary *dict =  [YKBusinessFramework register_user_info:ThirdPartyDemoBrand appkey:ThirdPartyDemoAppKey user_name:self.user_textfield.text];
    
    [AFNHTTPSRequest httpsPostRequestWithUrl:[YKBusinessFramework register_user] errorHint:^(id  _Nonnull errorData) {
        NSLog(@"errorData -- %@",errorData);
    } deleteDic:dict isFavorite:YES result:^(id  _Nonnull data) {
        NSLog(@"data -- %@",data);
        
        if ([[data objectForKey:@"code"] intValue] == 0) {
            
            
            [SVProgressHUD showSuccessWithStatus:@"注册成功！"];
            
            NSString *token = [data objectForKey:@"data"];
            self.token = token;
            self.pwd_textfield.text = token;
            // @"f358783c7bea2c9a626dce7706627d4c"

            
            /*
             2.拿到用户名和token 去 登录
             
              登录成功后 保存token 以供下次自动登录获取
            
             */
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
              
                [YKBusinessFramework loginWithUserName:self.user_textfield.text token:token appKey:ThirdPartyDemoAppKey server_adds:SERVER_ADDRS];
            });
             
            
            
            
        }else if ([[data objectForKey:@"code"] intValue] == 4404){
            
           
            [SVProgressHUD showErrorWithStatus:@"用户已注册"];
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:[data objectForKey:@"reason"]];
    
        }
        
            /*
             data -- {
                 code = 0;
                 data = f358783c7bea2c9a626dce7706627d4c; // 注册成功返回的token
                 reason = success;
             }
             */
            
    }];
    
}


@end
